<?php
namespace app\common\service\collect;

use app\common\service\CollectService;

/**
 * 采集1688商品数据处理服务
 *
 * @Description
 * @package app\common\service\collect
 * @author wangqinghui
 * @date 2024-10-25 09:00
 */
class Collect1688Service extends CollectService{

    /**
     * 处理采集数据
     *
     * @Description
     * @author wangqinghui
     * @date 2024-10-25 10:59
     * @param string $html
     * @param string $url
     * @return Collect1688Service
     */
    public function handel(string $html = '', string $url = '') : Collect1688Service
    {
        if(empty($html)){
            throw new \Exception('暂无需要采集的数据');
        }
        preg_match('/window.__INIT_DATA=(.*})|window.contextPath,(\{.*\})/', $html, $matches);
        if(empty($matches[0])){
            throw new \Exception('暂未获取到数据');
        }
        $content = !empty($matches[1]) ? $matches[1] : (!empty($matches[2]) ? $matches[2] : '');
        $info_arr = json_decode($content, 1);
        if(empty($info_arr)){
            throw new \Exception('暂未获取到数据');
        }
        $baseData = $info_arr['data'] ?? [];
        $new_result_data = $info_arr['result'] ?? [];
        if(empty($baseData) && empty($new_result_data)){
            throw new \Exception('商品数据缺失');
        }
        if(!empty($baseData)){
            $globalData = $info_arr['globalData'] ?? [];
            // 获取商品属性及SKU
            $skuData = $globalData['skuModel'] ?? [];
            // 获取属性数据
            $arrKeyData = $attrImgData = $skuArr= [];
            if(!empty($skuData)){
                $skuPropArr = $skuData['skuProps'] ?? [];
                $skuInfoMapArr = $skuData['skuInfoMap'] ?? [];
                if(!empty($skuPropArr) && is_array($skuPropArr)){
                    foreach ($skuPropArr as $key => $value){
                        if(!empty($value['value']) && is_array($value['value'])){
                            foreach ($value['value'] as $item){
                                $arrKeyData[$value['prop']][$item['name']] = $item;
                                $attrImgData[$item['name']] = $item['imageUrl'] ?? '';
                            }
                        }
                    }
                }
                // 获取sku数据
                if(!empty($skuInfoMapArr) && is_array($skuInfoMapArr)){
                    foreach ($skuInfoMapArr as $key => $value){
                        $specAttrsArr = !empty($value['specAttrs']) ? explode('&gt;', $value['specAttrs']) : [];
                        $sku_image = !empty($attrImgData[$specAttrsArr[0]]) ? $attrImgData[$specAttrsArr[0]] : '';
                        $value['skuImage'] = $sku_image;
                        $value['stock'] = $value['canBookCount'];
                        $value['title'] = implode('-', $specAttrsArr);
                        $value['pe_price'] = !empty($value['discountPrice']) ? $value['discountPrice'] : (!empty($value['price']) ? $value['price'] : 0.00);
                        $skuArr[$value['skuId']] = $value;
                    }
                }
            }
            // 商品基础信息
            $product_info = $globalData['tempModel'] ?? [];
            $desc_content = $detail_content = '';
            $imgArr = [];
            if(!empty($baseData) && is_array($baseData)){
                foreach ($baseData as $key => $value){
                    // 获取商品属性描述
                    if(!empty($value['componentType']) && (($value['componentType'] == '@ali/tdmod-od-pc-attribute-new') || ($value['componentType'] == '@ali/tdmod-od-pc-attribute'))){
                        if(!empty($value['data']) && is_array($value['data'])){
                            foreach($value['data'] as $item){
                                $desc_content.= $item['name'].'：'.$item['value']."\n";
                            }
                        }
                    }
                    // 获取商品主图
                    if(!empty($value['componentType']) && (($value['componentType'] == '@ali/tdmod-pc-od-main-pic') || ($value['componentType'] == '@ali/tdmod-od-gyp-pc-main-pic'))){
                        $imgArr = !empty($value['data']['offerImgList']) ? $value['data']['offerImgList'] : [];
                    }
                    // 获取商品详情描述
                    if(!empty($value['componentType']) && ($value['componentType'] == '@ali/tdmod-od-pc-offer-description')){
                        $detail_url = $value['data']['detailUrl'] ?? '';
                        if(!empty($detail_url)){
                            $ret_content = http_get($detail_url);
                            if(!empty($ret_content)){
                                preg_match('/offer_details=(\s*{.*});$/', $ret_content, $ret_matches);
                                $office_details = !empty($ret_matches[1]) ? json_decode($ret_matches[1], 1) : [];
                                $detail_content = $office_details['content'] ?? '';
                            }
                        }
                    }
                    // 获取商品长、宽、高、重量、体积等
                    if(!empty($value['componentType']) && ($value['componentType'] == '@ali/tdmod-od-pc-offer-cross')){
                        $pieceWeightScaleInfo = !empty($value['data']['pieceWeightScale']['pieceWeightScaleInfo']) ? $value['data']['pieceWeightScale']['pieceWeightScaleInfo'] : [];
                        if(!empty($pieceWeightScaleInfo) && is_array($pieceWeightScaleInfo)){
                            foreach ($pieceWeightScaleInfo as $item){
                                $skuArr[$item['skuId']] = array_merge($skuArr[$item['skuId']], $item);
                            }
                        }
                    }
                }
            }
        }elseif(!empty($new_result_data)){
            $globalData = $new_result_data['global']['globalData'] ?? [];
            $desc_content = $detail_content = '';
            $imgArr = [];
            if(isset($globalData['model']['offerDetail'])){
                // 获取商品属性描述
                if(!empty($globalData['model']['offerDetail']['featureAttributes']) && is_array($globalData['model']['offerDetail']['featureAttributes'])){
                    foreach($globalData['model']['offerDetail']['featureAttributes'] as $item){
                        $desc_content.= $item['name'].'：'.$item['value']."\n";
                    }
                }
                // 获取商品详情描述
                if(!empty($globalData['model']['offerDetail']['detailUrl'])){
                    $detail_url = $globalData['model']['offerDetail']['detailUrl'];
                    $ret_content = http_get($detail_url);
                    if(!empty($ret_content)){
                        preg_match('/offer_details=(\s*{.*});$/', $ret_content, $ret_matches);
                        $office_details = !empty($ret_matches[1]) ? json_decode($ret_matches[1], 1) : [];
                        $detail_content = $office_details['content'] ?? '';
                    }
                }
            }
            if(!empty($new_result_data['data'])){
                if(isset($new_result_data['data']['Root'])){
                    // 商品基础信息
                    $product_info = $new_result_data['data']['Root']['fields']['dataJson']['tempModel'] ?? [];
                    // 获取商品属性及SKU
                    $skuData = $new_result_data['data']['Root']['fields']['dataJson']['skuModel'] ?? [];
                    // 获取属性数据
                    $arrKeyData = $attrImgData = $skuArr= [];
                    if(!empty($skuData)){
                        $skuPropArr = $skuData['skuProps'] ?? [];
                        $skuInfoMapArr = $skuData['skuInfoMap'] ?? [];
                        if(!empty($skuPropArr) && is_array($skuPropArr)){
                            foreach ($skuPropArr as $key => $value){
                                if(!empty($value['value']) && is_array($value['value'])){
                                    foreach ($value['value'] as $item){
                                        $arrKeyData[$value['prop']][$item['name']] = $item;
                                        $attrImgData[$item['name']] = $item['imageUrl'] ?? '';
                                    }
                                }
                            }
                        }
                        // 获取sku数据
                        if(!empty($skuInfoMapArr) && is_array($skuInfoMapArr)){
                            foreach ($skuInfoMapArr as $key => $value){
                                $specAttrsArr = !empty($value['specAttrs']) ? explode('&gt;', $value['specAttrs']) : [];
                                $sku_image = !empty($attrImgData[$specAttrsArr[0]]) ? $attrImgData[$specAttrsArr[0]] : '';
                                $value['skuImage'] = $sku_image;
                                $value['stock'] = $value['canBookCount'];
                                $value['title'] = implode('-', $specAttrsArr);
                                $value['pe_price'] = !empty($value['discountPrice']) ? $value['discountPrice'] : (!empty($value['price']) ? $value['price'] : 0.00);
                                $skuArr[$value['skuId']] = $value;
                            }
                        }
                    }
                }
                // 获取商品主图
                if(isset($new_result_data['data']['gallery'])){
                    $imgArr = !empty($new_result_data['data']['gallery']['fields']['offerImgList']) ? $new_result_data['data']['gallery']['fields']['offerImgList'] : [];
                }
                // // 获取商品详情描述
                // if(isset($new_result_data['data']['description']['fields'])){
                //     $detail_url = $new_result_data['data']['description']['fields']['detailUrl'] ?? '';
                //     if(!empty($detail_url)){
                //         $ret_content = http_get($detail_url);
                //         if(!empty($ret_content)){
                //             preg_match('/offer_details=(\s*{.*});$/', $ret_content, $ret_matches);
                //             $office_details = !empty($ret_matches[1]) ? json_decode($ret_matches[1], 1) : [];
                //             $detail_content = $office_details['content'] ?? '';
                //         }
                //     }
                // }
                // 获取商品长、宽、高、重量、体积等
            }
        }
        
        // 获取商品分类名称

        // 组装商品信息
        $goods_info = [
            'title'     =>    $product_info['offerTitle'] ?? '', // 商品标题
            'desc'      =>    $desc_content ?? '',// 商品属性描述
            'detail'    =>    $detail_content ?? '',// 商品详情描述
            'goods_code'    =>    $product_info['offerId'] ?? '',// 采集商品ID
            'url'       =>    $url ?? '', // 商品链接
            'platform'  => 1, // 1688平台
            // 'price'      =>    !empty($skuData['skuPriceScale']) ? str_replace('￥', '', $skuData['skuPriceScale']) : '', // 商品价格范围
            'min_price'     =>    !empty($skuArr) ? min(array_column($skuArr, 'pe_price')) : 0.00,// 商品最低价格
            'max_price'     =>    !empty($skuArr) ? max(array_column($skuArr, 'pe_price')) : 0.00,// 商品最高价格
            'shop_name'     =>    $product_info['companyName'] ?? '', // 店铺名称
            'category_code' =>    $product_info['postCategoryId'] ?? '', // 商品分类ID
            'category_name' =>    $product_info['categoryName'] ?? '', // 商品分类名称
        ];
        // 设置组装数据
        $this->assemberGoodsData($goods_info, $imgArr, $arrKeyData, $skuArr);
        return $this;
    }

    /**
     * 组装采集的入库数据
     *
     * @Description
     * @author wangqinghui
     * @date 2024-10-24 18:15
     * @param array $goods_info
     * @param array $imgArr
     * @param array $arrKeyData
     * @param array $skuArr
     * @return Collect1688Service
     */
    protected function assemberGoodsData(array $goods_info, array $imgArr, array $arrKeyData, array $skuArr) :Collect1688Service
    {
        $this->assember_goods_data['goods'] = $goods_info;
        $this->assember_goods_data['images'] = $imgArr;
        $this->assember_goods_data['attrs'] = $arrKeyData;
        $this->assember_goods_data['skus'] = $skuArr;
        return $this;
    }
}